<template>
  <div class="address-manager">
    <!-- 头部 -->
    <header class="header">
      <i class="fas fa-arrow-left back-btn" @click="goBack" v-if="showBackButton"></i>
      <h1>{{ isAdding ? (editingAddressId ? '编辑地址' : '新增地址') : '我的地址' }}</h1>
      <div class="header-placeholder"></div>
    </header>

    <!-- 主要内容 -->
    <main class="main-content">
      <!-- 地址列表 -->
      <div class="address-list" v-if="!isAdding && !isEditing">
        <div v-if="loading" class="loading-state">
          <i class="fas fa-spinner fa-spin"></i>
          <p>加载中...</p>
        </div>

        <div v-else-if="addresses.length === 0" class="empty-state">
          <i class="fas fa-map-marker-alt empty-icon"></i>
          <p class="empty-text">暂无收货地址</p>
          <p class="empty-subtext">请添加您的收货地址</p>
        </div>

        <div v-else class="addresses-container">
          <div
              v-for="address in addresses"
              :key="address.id"
              class="address-item"
          >
            <div class="address-main" @click="selectAddress(address)">
              <div class="address-header">
                <span class="address-name">{{ address.contactName }}</span>
                <span class="address-gender">{{ address.contactSex === 1 ? '先生' : '女士' }}</span>
              </div>

              <div class="address-phone">{{ formatPhoneNumber(address.contactTel) }}</div>

              <div class="address-content">
                {{ address.address }}
              </div>
            </div>

            <div class="address-actions">
              <button class="action-btn edit-btn" @click.stop="editAddress(address.id)">
                <i class="fas fa-edit"></i> 编辑
              </button>
              <button class="action-btn delete-btn" @click.stop="deleteAddress(address.id)">
                <i class="fas fa-trash"></i> 删除
              </button>
            </div>
          </div>
        </div>

        <button class="add-address-btn" @click="showAddForm">
          <i class="fas fa-plus"></i> 新增收货地址
        </button>
      </div>

      <!-- 地址表单 -->
      <div class="address-form" v-else>
        <form @submit.prevent="saveAddress">
          <div class="form-group">
            <label>联系人</label>
            <input
                type="text"
                v-model="currentAddress.contactName"
                placeholder="请输入收货人姓名"
                maxlength="20"
                required
            >
          </div>

          <div class="form-group">
            <label>性别</label>
            <div class="gender-options">
              <label class="gender-option">
                <input
                    type="radio"
                    v-model="currentAddress.contactSex"
                    :value="1"
                    required
                >
                <span class="gender-text">先生</span>
              </label>
              <label class="gender-option">
                <input
                    type="radio"
                    v-model="currentAddress.contactSex"
                    :value="0"
                >
                <span class="gender-text">女士</span>
              </label>
            </div>
          </div>

          <div class="form-group">
            <label>手机号码</label>
            <input
                type="tel"
                v-model="currentAddress.contactTel"
                placeholder="请输入11位手机号码"
                maxlength="11"
                required
            >
          </div>

          <div class="form-group">
            <label>收货地址</label>
            <textarea
                v-model="currentAddress.address"
                placeholder="请输入详细收货地址，如：XX省XX市XX区XX街道XX号"
                rows="3"
                maxlength="200"
                required
            ></textarea>
          </div>

          <div class="form-actions">
            <button type="submit" class="btn btn-primary" :disabled="saving">
              {{ saving ? '保存中...' : (editingAddressId ? '更新地址' : '保存地址') }}
            </button>
            <button type="button" class="btn btn-secondary" @click="cancelEdit" :disabled="saving">
              取消
            </button>
          </div>
        </form>
      </div>
    </main>

    <!-- 底部导航 -->
    <Footer v-if="!isAdding && !isEditing" />

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-message" @click="errorMessage = ''">
      <i class="fas fa-exclamation-circle"></i> {{ errorMessage }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Footer from '../components/Footer.vue'
import { addressAPI } from '@/api/address.js'

export default {
  name: 'UserAddress',
  components: {
    Footer
  },
  setup() {
    const route = useRoute()
    const router = useRouter()

    const addresses = ref([])
    const loading = ref(false)
    const saving = ref(false)
    const errorMessage = ref('')
    const isAdding = ref(false)
    const isEditing = ref(false)
    const editingAddressId = ref(null)

    const currentAddress = ref({
      contactName: '',
      contactSex: 1,
      contactTel: '',
      address: ''
    })

    const businessId = ref(route.query.businessId)
    const fromOrder = ref(route.query.from === 'order')

    const showBackButton = computed(() => {
      return isAdding.value || isEditing.value || fromOrder.value
    })

    // 格式化手机号显示
    const formatPhoneNumber = (phone) => {
      if (!phone) return ''
      return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1 **** $3')
    }

    // 加载地址列表
    const loadAddresses = async () => {
      loading.value = true
      errorMessage.value = ''

      try {
        const response = await addressAPI.getUserAddresses()
        if (response.data && response.data.success) {
          addresses.value = response.data.data || []
        } else {
          errorMessage.value = response.data?.message || '获取地址列表失败'
        }
      } catch (error) {
        console.error('加载地址失败:', error)
        errorMessage.value = '获取地址列表失败，请重试'
      } finally {
        loading.value = false
      }
    }

    // 显示添加表单
    const showAddForm = () => {
      isAdding.value = true
      editingAddressId.value = null
      currentAddress.value = {
        contactName: '',
        contactSex: 1,
        contactTel: '',
        address: ''
      }
    }

    // 编辑地址
    const editAddress = (id) => {
      const address = addresses.value.find(addr => addr.id === id)
      if (address) {
        isEditing.value = true
        editingAddressId.value = id
        currentAddress.value = { ...address }
      }
    }

    // 取消编辑
    const cancelEdit = () => {
      isAdding.value = false
      isEditing.value = false
      editingAddressId.value = null
      currentAddress.value = {
        contactName: '',
        contactSex: 1,
        contactTel: '',
        address: ''
      }
    }

    // 保存地址
    const saveAddress = async () => {
      // 表单验证
      if (!validateForm()) {
        return
      }

      saving.value = true
      errorMessage.value = ''

      try {
        if (editingAddressId.value) {
          // 更新地址
          const response = await addressAPI.updateAddress(editingAddressId.value, currentAddress.value)
          if (response.data && response.data.success) {
            await loadAddresses() // 重新加载列表
            cancelEdit()
          } else {
            errorMessage.value = response.data?.message || '更新地址失败'
          }
        } else {
          // 新增地址
          const addressData = { ...currentAddress.value }
          const response = await addressAPI.addAddress(addressData)
          if (response.data && response.data.success) {
            await loadAddresses() // 重新加载列表
            cancelEdit()
          } else {
            errorMessage.value = response.data?.message || '新增地址失败'
          }
        }
      } catch (error) {
        console.error('保存地址失败:', error)
        errorMessage.value = '操作失败，请重试'
      } finally {
        saving.value = false
      }
    }

    // 表单验证
    const validateForm = () => {
      if (!currentAddress.value.contactName.trim()) {
        errorMessage.value = '请输入联系人姓名'
        return false
      }

      if (!currentAddress.value.contactTel.trim()) {
        errorMessage.value = '请输入手机号码'
        return false
      }

      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(currentAddress.value.contactTel)) {
        errorMessage.value = '请输入有效的11位手机号码'
        return false
      }

      if (!currentAddress.value.address.trim()) {
        errorMessage.value = '请输入收货地址'
        return false
      }

      return true
    }

    // 删除地址
    const deleteAddress = async (id) => {
      if (!confirm('确定要删除这个地址吗？')) return

      try {
        const response = await addressAPI.deleteAddress(id)
        if (response.data && response.data.success) {
          await loadAddresses() // 重新加载列表
        } else {
          errorMessage.value = response.data?.message || '删除地址失败'
        }
      } catch (error) {
        console.error('删除地址失败:', error)
        errorMessage.value = '删除地址失败，请重试'
      }
    }

    // 选择地址（用于订单页面）
    const selectAddress = (address) => {
      if (fromOrder.value) {
        // 将选择的地址传递回订单页面
        sessionStorage.setItem('selectedAddress', JSON.stringify(address))
        router.back()
      }
    }

    // 返回上一页
    const goBack = () => {
      if (isAdding.value || isEditing.value) {
        cancelEdit()
      } else if (fromOrder.value) {
        router.back()
      } else {
        router.push('/userProfile')
      }
    }

    onMounted(() => {
      loadAddresses()
    })

    return {
      addresses,
      loading,
      saving,
      errorMessage,
      isAdding,
      isEditing,
      editingAddressId,
      currentAddress,
      businessId,
      fromOrder,
      showBackButton,
      formatPhoneNumber,
      showAddForm,
      editAddress,
      cancelEdit,
      saveAddress,
      deleteAddress,
      selectAddress,
      goBack
    }
  }
}
</script>

<style scoped>
.address-manager {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 50px;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #0097ff, #0077cc);
  color: white;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.back-btn {
  font-size: 18px;
  cursor: pointer;
  padding: 5px;
}

.header h1 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.header-placeholder {
  width: 24px;
}

/* 主要内容 */
.main-content {
  padding: 15px;
}

/* 地址列表 */
.addresses-container {
  margin-bottom: 20px;
}

.address-item {
  background: white;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border-left: 4px solid #0097ff;
}

.address-main {
  margin-bottom: 15px;
  cursor: pointer;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.address-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-right: 8px;
}

.address-gender {
  font-size: 14px;
  color: #666;
  margin-right: 10px;
}

.address-phone {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.address-content {
  font-size: 14px;
  color: #333;
  line-height: 1.4;
}

.address-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.edit-btn {
  background: #3498db;
  color: white;
}

.delete-btn {
  background: #e74c3c;
  color: white;
}

.action-btn:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

/* 新增地址按钮 */
.add-address-btn {
  width: 100%;
  padding: 15px;
  background: linear-gradient(135deg, #0097ff, #0077cc);
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s;
}

.add-address-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 151, 255, 0.3);
}

/* 地址表单 */
.address-form {
  background: white;
  border-radius: 10px;
  padding: 20px;
  margin-top: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #333;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #0097ff;
  box-shadow: 0 0 0 2px rgba(0, 151, 255, 0.1);
}

.gender-options {
  display: flex;
  gap: 20px;
}

.gender-option {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.gender-option input {
  width: auto;
  margin-right: 8px;
}

.gender-text {
  font-weight: normal;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 30px;
}

.btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-primary {
  background: #0097ff;
  color: white;
}

.btn-primary:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.btn-secondary {
  background: #95a5a6;
  color: white;
}

.btn-secondary:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #7f8c8d;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 15px;
  color: #bdc3c7;
}

.empty-text {
  font-size: 16px;
  margin-bottom: 8px;
  font-weight: 600;
}

.empty-subtext {
  font-size: 14px;
  color: #95a5a6;
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 60px 20px;
  color: #0097ff;
}

.loading-state i {
  font-size: 32px;
  margin-bottom: 15px;
}

/* 错误提示 */
.error-message {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: #e74c3c;
  color: white;
  padding: 12px 20px;
  border-radius: 6px;
  font-size: 14px;
  z-index: 1000;
  max-width: 90%;
  text-align: center;
  cursor: pointer;
}

.error-message i {
  margin-right: 8px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .address-actions {
    flex-direction: column;
  }

  .action-btn {
    width: 100%;
  }

  .form-actions {
    flex-direction: column;
  }
}
</style>